package fcrypt

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"os"
)

func GenerateRSAKey() error {
	//生成密钥对，key中包含了私钥和公钥
	key, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		panic(err)
	}

	//先做私钥
	//生成der格式的私钥字节数组
	derPrivateKey := x509.MarshalPKCS1PrivateKey(key)
	//创建一个私钥文件
	privateKeyFile, err := os.Create("./privatekey.pem")
	if err != nil {
		panic(err)
	}
	//将私钥信息写入到文件中
	block := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: derPrivateKey,
	}
	if err := pem.Encode(privateKeyFile, block); err != nil {
		panic(err)
	}

	//再做公钥
	publicKey := &key.PublicKey
	derPublicKey, err := x509.MarshalPKIXPublicKey(publicKey)
	if err != nil {
		panic(err)
	}
	publicKeyFile, err := os.Create("./publickey.pem")
	if err != nil {
		panic(err)
	}

	block = &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: derPublicKey,
	}
	if err := pem.Encode(publicKeyFile, block); err != nil {
		panic(err)
	}

	return nil
}

func ReadPublicKey(file string) (*rsa.PublicKey, error) {
	publicKeyByte, err := ioutil.ReadFile(file)
	if err != nil {
		fmt.Printf("read public key file err = %v", err)
		return nil, err
	}
	block, _ := pem.Decode(publicKeyByte)
	if block == nil {
		fmt.Printf("public key pem decode err")
		return nil, nil
	}
	publicKeyer, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		fmt.Printf("parse public key err = %v", err)
		return nil, err
	}
	publicKey := publicKeyer.(*rsa.PublicKey)
	return publicKey, nil
}

func ReadPrivateKey(file string) (*rsa.PrivateKey, error) {
	privateKeyByte, err := ioutil.ReadFile(file)
	if err != nil {
		fmt.Printf("read private key file err = %v", err)
		return nil, err
	}
	block, _ := pem.Decode(privateKeyByte)
	if block == nil {
		fmt.Printf("private key pem decode err")
		return nil, nil
	}

	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		fmt.Printf("parse private key err = %v", err)
		return nil, err
	}
	return privateKey, nil
}
